﻿using CommunityToolkit.Mvvm.Messaging;
using Main.Configs;
using Main.Messages;
using Main.Tools;
using Main.ViewModels;
using Microsoft.EntityFrameworkCore.Storage;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace Main.Views
{
    /// <summary>
    /// PrintingWindow.xaml 的交互逻辑
    /// </summary>
    public partial class PrintingWindow : Window
    {
        PrintDialog _print_dlg;        
        bool _is_printing = false;

        IDbContextTransaction _transaction = null;
        public PrintingWindow()
        {
            InitializeComponent();

            //打印
            btnPrint.Click +=  async(o, e) =>
            {
                if(_print_dlg != null)
                {
                    bool? print = _print_dlg.ShowDialog();
                    if (print == true)
                    {
                        //保存打印设置
                        VoucherPrintConfig.Current.PrintQueueName = _print_dlg.PrintQueue.FullName;
                        if (_print_dlg.PrintTicket.PageMediaType != null)
                        {
                            VoucherPrintConfig.Current.PageMediaType = _print_dlg.PrintTicket.PageMediaType.Value;
                        }
                        if (_print_dlg.PrintTicket.PageOrientation != null)
                        {
                            VoucherPrintConfig.Current.PageOrientation = _print_dlg.PrintTicket.PageOrientation.Value;
                        }
                        if (_print_dlg.PrintTicket.PageMediaSize.PageMediaSizeName != null)
                        {
                            VoucherPrintConfig.Current.PageMediaSizeName = _print_dlg.PrintTicket.PageMediaSize.PageMediaSizeName.Value;
                        }
                        if (_print_dlg.PrintTicket.PageMediaSize.Width != null)
                        {
                            VoucherPrintConfig.Current.PageWidth = _print_dlg.PrintTicket.PageMediaSize.Width.Value;
                        }
                        if (_print_dlg.PrintTicket.PageMediaSize.Height != null)
                        {
                            VoucherPrintConfig.Current.PageHeight = _print_dlg.PrintTicket.PageMediaSize.Height.Value;
                        }
                        VoucherPrintConfig.Current.Save();

                        //设置打印区大小
                        paper.Width = _print_dlg.PrintableAreaWidth;
                        paper.Height = paper.Width * VoucherPrintConfig.Current.VoucherHeight / VoucherPrintConfig.Current.VoucherWidth;
                        container.Width = paper.Width;


                        //打印
                        await _Print();
                    }
                }
            };

            //停止打印
            btnPrintStop.Click += (o, e) =>
            {
                if (MessageBox.Show("您确定要取消吗？",
                    "取消打印",
                    MessageBoxButton.YesNo,
                    MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    Serilog.Log.Information($"【凭证打印】用户取消");

                    if(_transaction!=null)
                    {
                        _transaction.Rollback();
                        _transaction.Dispose();
                        Serilog.Log.Information($"【数据】用户取消，回滚事务");
                    }                    
                    this.Close();
                }                            
            };


            WeakReferenceMessenger.Default.Register<VoucherInfoMessage>(this, async (r, m) =>
            {
                this.DataContext = m.vm;

                //
                _print_dlg = m.print_dialog;


                //设置打印区大小
                paper.Width = _print_dlg.PrintableAreaWidth;
                paper.Height = paper.Width * VoucherPrintConfig.Current.VoucherHeight / VoucherPrintConfig.Current.VoucherWidth;
                container.Width = paper.Width;               

                
                if (!_is_printing)
                {
                    btnPrint.IsEnabled = true;
                }
                else//已经开始打印了
                {
                    if (checkboxConfirmEvery.IsChecked==false)
                    {
                        await _Print();
                    }
                }             
            });
            WeakReferenceMessenger.Default.Register<VoucherPrintDoneMessage>(this, (r, m) => {
                _transaction?.Commit();
                _transaction?.Dispose();
                Serilog.Log.Information($"【数据】打印完成，提交事务");
                this.Close();
            });


            Serilog.Log.Information($"【凭证打印】打印窗口准备好");
            WeakReferenceMessenger.Default.Send<VoucherPrintDlgReadyMessage>(new VoucherPrintDlgReadyMessage());


            _transaction= Database.ERPNext.ERPNextDbContext.Current.Database.BeginTransaction();
            Serilog.Log.Information($"【数据】开始事务");
        }

        private async Task _Print()
        {
            //
            _is_printing = true;
            btnPrint.IsEnabled = false;
            
            
            await Dispatcher.BeginInvoke(() => {
                var vm = this.DataContext as VoucherPrintPaperViewModel;
                if (vm != null)
                {
                    //打印到文件
                    var png_file = System.IO.Path.Combine(Directory.GetCurrentDirectory(), VoucherPrintConfig.Current.OutputFolder, $"{vm.VoucherNoDetail.Replace('/', '@')}.png");
                    ControlToImage.PrintVisualToFile(paper, (int)VoucherPrintConfig.Current.VoucherWidth * 10, (int)VoucherPrintConfig.Current.VoucherHeight * 10, png_file);


                //打印到纸张
                if (_print_dlg != null)
                    {
                        _print_dlg.PrintVisual(paper, "凭证打印");
                        if (checkboxConfirmEvery.IsChecked == true)
                        {
                            _is_printing = false;
                            btnPrint.IsEnabled = true;
                            
                        }
                    }

                    //打印完成，通知发送下一个凭证
                    Serilog.Log.Information($"【凭证打印】打印完成：{vm.VoucherNoDetail}");

                    //保存到数据库
                    
                    Database.ERPNext.tabVoucherPrintHistory history=new Database.ERPNext.tabVoucherPrintHistory();
                    history.print_time = DateTime.Now;
                    history.user_name=(Application.Current.MainWindow.DataContext as MainViewModel)!.User!;
                    history.voucher_detail_no = vm.VoucherNoDetail;
                    history.voucher_no = vm.VoucherNo;
                    Database.ERPNext.ERPNextDbContext.Current.TabVoucherPrintHistories.Add(history);
                    Database.ERPNext.ERPNextDbContext.Current.SaveChanges();
                }
                
                WeakReferenceMessenger.Default.Send<VoucherPrintDlgReadyMessage>(new VoucherPrintDlgReadyMessage());
            });
            

        }
    }
}
